from rest_framework import serializers
from .models import Conversation, Message, RetrievedDocument, QuestionFeedback


class RetrievedDocumentSerializer(serializers.ModelSerializer):
    """检索文档序列化器"""
    document_title = serializers.CharField(source='document.title', read_only=True)

    class Meta:
        model = RetrievedDocument
        fields = ['id', 'document', 'document_title', 'chunk_index',
                  'relevance_score', 'content', 'created_at']


class MessageSerializer(serializers.ModelSerializer):
    """消息序列化器"""
    retrieved_docs = RetrievedDocumentSerializer(many=True, read_only=True)

    class Meta:
        model = Message
        fields = ['id', 'conversation', 'role', 'content', 'tokens',
                  'model', 'retrieved_docs', 'created_at']
        read_only_fields = ['tokens', 'model', 'created_at']


class ConversationSerializer(serializers.ModelSerializer):
    """对话会话序列化器"""
    message_count = serializers.SerializerMethodField()
    last_message = serializers.SerializerMethodField()
    knowledge_base_name = serializers.CharField(source='knowledge_base.name', read_only=True)

    class Meta:
        model = Conversation
        fields = ['id', 'title', 'knowledge_base', 'knowledge_base_name',
                  'is_archived', 'message_count', 'last_message',
                  'created_at', 'updated_at']
        read_only_fields = ['user', 'created_at', 'updated_at']

    def get_message_count(self, obj):
        return obj.messages.count()

    def get_last_message(self, obj):
        last_msg = obj.messages.order_by('-created_at').first()
        if last_msg:
            return {
                'role': last_msg.role,
                'content': last_msg.content[:100],
                'created_at': last_msg.created_at
            }
        return None

    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class ConversationDetailSerializer(ConversationSerializer):
    """对话会话详情序列化器"""
    messages = MessageSerializer(many=True, read_only=True)

    class Meta(ConversationSerializer.Meta):
        fields = ConversationSerializer.Meta.fields + ['messages']


class AskQuestionSerializer(serializers.Serializer):
    """提问序列化器"""
    question = serializers.CharField(required=True, help_text='问题内容')
    conversation_id = serializers.IntegerField(required=False, help_text='对话ID(可选)')
    knowledge_base_id = serializers.IntegerField(
        required=False,
        allow_null=True,
        help_text='知识库ID(可选，支持为空走通用问答)'
    )
    use_rag = serializers.BooleanField(default=True, help_text='是否使用RAG')
    top_k = serializers.IntegerField(default=3, min_value=1, max_value=10, help_text='检索文档数量')


class QuestionFeedbackSerializer(serializers.ModelSerializer):
    """问答反馈序列化器"""

    class Meta:
        model = QuestionFeedback
        fields = '__all__'
        read_only_fields = ['user', 'created_at']

    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)
